<?php
//4
function manage_room_list_page() {
    @$output = drupal_render(drupal_get_form('manage_room_list_form'));
    return $output;
}
function manage_room_add_page(){
    @$output = drupal_render(drupal_get_form('manage_room_edit_form'));
    return $output;
}

function manage_room_edit_page($id){
    @$output = drupal_render(drupal_get_form('manage_room_edit_form',$id));
    return $output;
}

function manage_room_member_list_page(){
    @$output = drupal_render(drupal_get_form('manage_room_member_list_form'));
    return $output;
}

function manage_room_member_add_page(){
    @$output = drupal_render(drupal_get_form('manage_room_member_add_form'));
    return $output;
}


function manage_room_list_form($form, &$form_state)
{
    global $user;
    $res = db_select('chat_groups', 'CG')
        ->fields('CG', array('chat_group_id', 'chat_group_name'))
        ->condition('CG.chat_group_id',array(2,3),'not in')
        ->condition(db_or()->condition('CG.user_id',$user->uid,'=')->condition('CG.chat_group_id', 1, '='))
        ->execute();
    $options = ['' => ''];
    foreach ($res as $record) {
        $options[$record->chat_group_id] = $record->chat_group_name;
    }

    unset($options['']);
    $form['chat_group_assign'] = array(
        '#type' => 'select',
        '#default_value' => '1',
        '#validated' => TRUE,
        '#options'=> $options,
    );

    $form['button'] = array(
        '#type' => 'button',
        '#value' => '保存',
        '#attributes' => array('onclick' => "editfriend('group','','','')"),
    );
    $table['#markup'] = manage_chat_room_view_page($form, $form_state);
    $form['table'] = $table;
    return $form;
}

function manage_chat_room_view_page(&$form, &$form_state){
    global $user;
    $output = '';
    $header = array(
        array('data' => '选择', 'class' => ['no']),
        array('data' => '聊天群名称', 'class' => ['title']),
        array('data' => '聊天类别', 'class' => ['chat_group']),
        array('data' => '管理成员', 'class'=>['cz']),
        array('data' => '操作', 'class'=>['cz']),
        array('data' => '退出', 'class'=>['tc']),
    );
    $query = db_select('chat','C')->extend('PagerDefault')->extend('TableSort');
    $query->join('chat_users','CU','CU.chat_id = C.chat_id');
    $query->join('chat_groups', 'CG', 'CG.chat_group_id = CU.chat_group_id');
    $query->condition('CU.user_id',$user->uid);
    $query->condition('C.type',1);
    $query->condition('CU.active', '1', '=');
    $query->addField('CG', 'chat_group_name');
    $query->fields('C');
    $query->fields('CU');
    $query->limit(variable_get("list_page_item_number", 5));
    $result = $query->orderByHeader($header)->execute();
    $n = 1;
    foreach ($result as $row) {
        $rows[] = array(
            array('data' => '<input type="checkbox" class="listViewTableCheck" value ="' . $row->chat_id . '"/>' . $n++, 'class' => ['integrant essential no '.$row->chat_id]),
            array('data' => $row->title, 'class' => ['essential nickname '.$row->chat_id]),
            array('data' => $row->chat_group_name, 'class' => ['essential nickname '.$row->chat_id]),
            array('data' => '<a href="'.base_path().'manage_chat/member/list/'. $row->chat_id .'?id='. $row->chat_id .'" target="_blank"><img width="25px" height="25px" src="'.base_path().'sites/all/themes/tweme/images/images/room.png" style="cursor: pointer;"/></a>
            '),
            array('data' => '<a href="'.base_path().'manage_chat/room/edit/'. $row->chat_id .'" target="_self"><img width="25px" height="25px" src="'.base_path().'sites/all/themes/tweme/images/images/cz.png" style="cursor: pointer;"/></a>','class' => ['more']),
            array('data' => '<a href="'.base_path().'manage_chat/room/exit/'. $row->chat_id .'?id='. $row->chat_id .'" style="color: #000;display: block; margin-top: 2px;font-size:15px;text-decoration: none;" target="_self">退出该群</a>','class' => ['more']),
        );
    }
    $output .= theme('table', array('header' => $header, 'rows' => $rows, 'empty' => t('没有记录'), 'attributes' => array('class' => array('table table-bordered table-striped table-hover'))));
    $output .= theme('pager');
    return $output;
}

function manage_room_edit_form($form,&$form_state){
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    if (!empty($id)) {
        $record = room_load($id);
        if (empty($record)) {
            drupal_set_message(t('数据不存在！'), 'status', FALSE);
            drupal_goto('manage_chat/groups_list');
        }
        $form_state['id'] = $id;
    }

    $form['chat_room_title'] = array(
        '#type' => 'textfield',
        '#default_value' => !empty($record) ? $record->title:'',
        '#validated' => TRUE,
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => isset($record) ? '修改' : '添加',
//        '#access' => manage_room_add_form($form_state, $id),
    );
    return $form;
}

function manage_room_edit_form_validate(&$form, &$form_state) {
    if(empty($form_state['values']['chat_room_title'])){
        form_set_error('chat_room_title', '必须填写 聊天群名称');
    }
}

function manage_room_edit_form_submit(&$form,&$form_state){
    global $user;
    $user_info = _get_user_info($user->uid);
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    if (empty($id)) {
        $nid = db_insert('chat') // Table name no longer needs {}
        ->fields(array(
            'title' => $form_state['values']['chat_room_title'],
            'timestamp' => time()*1000,
            'type' =>1,
            'active' => 1,))
            ->execute();
        if ($nid > 0) {
            $res = db_insert('chat_users') // Table name no longer needs {}
            ->fields(array(
                'chat_id'=> $nid,
                'user_id' =>$user->uid,
                'nickname' => $user_info['name'],
                'chat_group_id' => 1,
                'active' => 1,
                'checkpoint' => 0))
                ->execute();
            drupal_set_message(t('添加成功！'), 'status', FALSE);
        }
    } else {
        $nid = db_update('chat') // edit exsting store. todo: update only modified fields
        ->fields(array(
            'title' => $form_state['values']['chat_room_title'],
            'timestamp' => time()*1000,))
            -> condition('chat_id',$id, '=')
            ->execute();
        if ($nid > 0) {
            drupal_set_message(t('修改成功！'), 'status', FALSE);
        }
    }
}

function manage_room_member_list_form($form,&$form_state){
    global $user;
    if(!empty($_GET['id'])){
        $form_state['room_id'] = $_GET['id'];
    }
    if(!empty($form_state['room_id'])){
        $form['#room_id'] = $form_state['room_id'];
    }
//    echo  $form['#room_id'];die;
    $form['nickname'] = array(
        '#type' => 'textfield',
        '#default_value' => '',
        '#attributes' => array('placeholder' => '好友姓名'),
    );
    $table['#markup'] =manage_room_member_list_view_page($form, $form_state);
    ajax_submit_form($form, $form_state, $table, '');
    return $form;
}


function manage_room_member_list_view_page(&$form,&$form_state){
    global $user;
    $output = '';
    $header = array(
        array('data' => '选择', 'class' => ['no']),
        array('data' => '好友名称', 'class' => ['nickname']),
//        array('data' => '操作', 'class' => ['cz']),
    );
    $rows = array();
    $query = db_select('chat','C')->extend('PagerDefault')->extend('TableSort');
    $query->join('chat_users','CU','CU.chat_id = C.chat_id');
    $query->join('chat_groups', 'CG', 'CG.chat_group_id = CU.chat_group_id');
    if(!empty($form_state['values']['nickname'])){
        $query->condition('CU.nickname', '%' . db_like($form_state['values']['nickname']) . '%', 'LIKE');
    }
//    $query->condition('CU.user_id',$user->uid);
    $query->condition('C.type',1);
    if(!empty($_GET['id'])){
        $form_state['list_chat_room_id'] = $_GET['id'];
    }
    if(!empty($form_state['list_chat_room_id'])){
        $form['#list_chat_room_id'] = $form_state['list_chat_room_id'];
    }
    $query->condition('CU.chat_id',$form_state['list_chat_room_id']);

    $query->condition('CU.active', '1', '=');
    $query->addField('CG', 'chat_group_name');
    $query->fields('C');
    $query->fields('CU');
    $query->limit(variable_get("list_page_item_number", 5));
    $result = $query->orderByHeader($header)->execute();
    $n = 1;
    foreach ($result as $row) {
        $rows[] = array(
            array('data' => '<input type="checkbox" class="listViewTableCheck" value ="' . $row->chat_id . '"/>' . $n++, 'class' => ['integrant essential no '.$row->chat_id]),
            array('data' => $row->nickname, 'class' => ['essential nickname '.$row->chat_id]),
//            array('data' => '<img width="25px" height="25px" src="'.base_path().'sites/all/themes/tweme/images/images/del-fri.png" style="cursor: pointer;" onclick="editfriend(\'del\',\''.$row->user_id.'\',\''.$row->nickname.'\',\''.$row->chat_id.'\')"/>'),
        );
    }

    $output .= theme('table', array('header' => $header, 'rows' => $rows, 'empty' => t('没有记录'), 'attributes' => array('class' => array('table table-bordered table-striped table-hover'))));
    $output .= theme('pager');
    return $output;
}


function manage_room_member_add_form($form,&$form_state){
    global $user;
    if(!empty($_GET['id'])){
        $form_state['room_id'] = $_GET['id'];
    }
    if(!empty($form_state['room_id'])){
        $form['#room_id'] = $form_state['room_id'];
    }
    $form['employee_name'] = array(
        '#type' => 'textfield',
        '#default_value' => '',
        '#attributes' => array('placeholder' => '姓名'),
    );
    $form['phone'] = array(
        '#type' => 'textfield',
        '#default_value' => '',
        '#attributes' => array('placeholder' => '电话'),
    );
    $query = db_select('chat','C');
    $query->join('chat_users','CU','CU.chat_id = C.chat_id');
    $query->condition('CU.user_id',$user->uid);
    $query->condition('C.type',1);
    $query->condition('CU.active', '1', '=');
    $query->fields('C',array('chat_id','title'));
    $result = $query->execute()->fetchAll();
    $chat_room_options[''] = '';
    foreach ($result as $record) {
        $chat_room_options[$record->chat_id] = $record->title;
    }
    $form['chat_room_assign'] = array(
        '#type' => 'select',
        '#default_value' => '',
        '#validated' => TRUE,
        '#options'=> $chat_room_options,
    );
    $form['button'] = array(
        '#type' =>'button',
        '#value' => '保存',
        '#attributes' => array('onclick' => "assign_chat_room()"),
    );
//    print_r($chat_room_options);die;
    $table['#markup'] =manage_room_member_add_view_page($form, $form_state);
    ajax_submit_form($form, $form_state, $table, '');
    return $form;
}


function manage_room_member_add_view_page(&$form,&$form_state){
    global $user;
    $output = '';
    $header = array(
        array('data' => '选择', 'class' => ['no']),
        array('data' => '好友名称', 'class' => ['nickname']),
//        array('data' => '操作', 'class' => ['more']),
    );
    $rows = array();
    $query = db_select('employee', 'E')->extend('PagerDefault')->extend('TableSort');
    $query->join('department', 'D', 'E.department_id = D.department_id');
    $query->fields('E');
    $query->addField('D','department_name');
    if(!empty($form_state['values']['employee_name'])){
        $query->condition('E.employee_name', '%' . db_like($form_state['values']['employee_name']) . '%', 'LIKE');
    }
    if(!empty($form_state['values']['phone'])){
        $query->condition('E.phone', '%' . db_like($form_state['values']['phone']) . '%', 'LIKE');
    }
    if(!empty($_GET['chat_room_id'])){
        $form_state['chat_room_id'] = $_GET['chat_room_id'];
        $user_ids = get_chatRoom_uid($form_state['chat_room_id']);
        $query->condition('E.employee_id',$user_ids,'not in');
    }
    if(!empty($form_state['chat_room_id'])){
        $user_ids = get_chatRoom_uid($form_state['chat_room_id']);
        $query->condition('E.employee_id',$user_ids,'not in');
    }

    $query->limit(variable_get("list_page_item_number", 5));
    $result = $query->orderByHeader($header)->execute();
    $n = 1;
    foreach ($result as $row) {
        $rows[] = array(
            array('data' => '<input type="checkbox" class="listViewTableCheck" value ="' . $row->employee_id . '"/>' . $n++, 'class' => ['integrant essential no '.$row->employee_id]),
            array('data' => $row->employee_name, 'class' => ['essential nickname '.$row->employee_id]),
//            array('data' => '<img width="25px" height="25px" src="'.base_path().'sites/all/themes/tweme/images/images/del-fri.png" style="cursor: pointer;"/>'),
        );
    }

    $output .= theme('table', array('header' => $header, 'rows' => $rows, 'empty' => t('没有记录'), 'attributes' => array('class' => array('table table-bordered table-striped table-hover'))));
    $output .= theme('pager');
    return $output;
}



function assign_chat_room(){
    $ids =$_POST['ids'];
    $chat_room_id = $_POST['chat_room_id'];
    $employee_name_array = db_select('employee','E')
        ->fields('E',array('employee_id','employee_name'))
        ->execute()->fetchAll();
    foreach($employee_name_array as $key => $value){
        $employee_name[$value->employee_id] =$value->employee_name;
    }
    $chat_group_id = db_select('chat_users','CU')
        ->condition('CU.chat_id',$chat_room_id)
        ->Fields('CU',array('chat_group_id'))
        ->execute()->fetchObject();
    foreach($ids as $k=>$v){

        $message = db_select('chat_users','C')
            ->condition('C.chat_id',$chat_room_id,'=')
            ->condition('C.user_id',$v,'=')
            ->condition('C.active','0','=')
            ->fields('C')
            ->execute()->fetchObject();
        if(!empty($message)){
            $nid = db_update('chat_users')->fields(
                array(
                    'active'=>1
                )
            )
            ->condition('chat_id',$chat_room_id,'=')
            ->condition('user_id',$v,'=')
            ->execute();
        }else{
            $nid = db_insert('chat_users')
                ->fields(array(
                'chat_id'=> $chat_room_id,
                'user_id' =>$v,
                'nickname' => $employee_name[$v],
                'chat_group_id' =>$chat_group_id->chat_group_id,
                'active' => 1,
                'checkpoint' => 0))
                ->execute();
        }
    }
    if($nid > 0){
        $result = array('success' => 1, 'errorNum' =>0);
    }else{
        $result = array('success' => 0, 'errorNum' =>1,'msg'=>'聊天群里已经有他了哦~');
    }
    echo json_encode($result);
}


function get_chatRoom_uid($chat_id){
    $res = db_select('chat_users','CU')
        ->condition('CU.chat_id',$chat_id)
        ->fields("CU",array('user_id'))
        ->execute()->fetchAll();
    foreach($res as $k=>$v){
        $user_ids[$v->user_id] = $v->user_id;
    }
//    print_r($user_ids);
    return $user_ids;
}


function room_load($id) {
    $result = db_select('chat', 'C')
        -> fields('C')
        -> condition('C.chat_id',$id, '=')
        -> execute()
        -> fetchObject();
    return $result;
}


function manage_room_exit(){
    global $user;
    $chat_id = arg(3)?arg(3):$_GET['id']?$_GET['id']:0;
    db_update('chat_users')
    ->fields(array(
        'active'=>0
        )
    )
    -> condition('chat_id',$chat_id, '=')
    ->condition('user_id',$user->uid,'=')
    ->execute();
    drupal_set_message(t('退出成功！'), 'status', FALSE);
    drupal_goto('manage_chat/room/list');
}